package com.scheduling.common.exception;

import com.scheduling.common.result.Result;
import com.scheduling.common.result.ResultCode;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 全局异常处理器
 *
 * @author 开发团队
 * @since 2025-06-02
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理请求体参数验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Result<Void>> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        log.warn("请求参数验证失败: {}", ex.getMessage());

        List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();
        String errorMessage = fieldErrors.stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining(", "));

        Result<Void> result = Result.error(ResultCode.PARAM_ERROR.getCode(), errorMessage);
        return ResponseEntity.badRequest().body(result);
    }

    /**
     * 处理表单参数验证异常
     */
    @ExceptionHandler(BindException.class)
    public ResponseEntity<Result<Void>> handleBindException(BindException ex) {
        log.warn("表单参数验证失败: {}", ex.getMessage());

        List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();
        String errorMessage = fieldErrors.stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining(", "));

        Result<Void> result = Result.error(ResultCode.PARAM_ERROR.getCode(), errorMessage);
        return ResponseEntity.badRequest().body(result);
    }

    /**
     * 处理单个参数验证异常
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseEntity<Result<Void>> handleConstraintViolationException(ConstraintViolationException ex) {
        log.warn("参数约束验证失败: {}", ex.getMessage());

        String errorMessage = ex.getConstraintViolations().stream()
                .map(ConstraintViolation::getMessage)
                .collect(Collectors.joining(", "));

        Result<Void> result = Result.error(ResultCode.PARAM_ERROR.getCode(), errorMessage);
        return ResponseEntity.badRequest().body(result);
    }

    /**
     * 处理参数类型转换异常
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public ResponseEntity<Result<Void>> handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException ex) {
        log.warn("参数类型转换失败: {}", ex.getMessage());

        String errorMessage = String.format("参数 '%s' 的值 '%s' 类型不正确",
                ex.getName(), ex.getValue());

        Result<Void> result = Result.error(ResultCode.PARAM_ERROR.getCode(), errorMessage);
        return ResponseEntity.badRequest().body(result);
    }

    /**
     * 处理业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<Result<Void>> handleBusinessException(BusinessException ex) {
        log.warn("业务异常: {}", ex.getMessage());

        // 获取业务异常的错误码，如果没有则使用默认业务错误码
        String code = ex.getCode();
        if (code == null || code.isEmpty()) {
            Result<Void> result = Result.error(ResultCode.BUSINESS_ERROR.getCode(), ex.getMessage());
            return ResponseEntity.ok(result);
        }

        // 尝试将字符串错误码转换为整数
        try {
            int errorCode = Integer.parseInt(code);
            Result<Void> result = Result.error(errorCode, ex.getMessage());
            return ResponseEntity.ok(result);
        } catch (NumberFormatException e) {
            // 如果转换失败，使用默认业务错误码
            Result<Void> result = Result.error(ResultCode.BUSINESS_ERROR.getCode(), ex.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 处理其他未知异常
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Result<Void>> handleException(Exception ex) {
        log.error("系统异常: ", ex);

        Result<Void> result = Result.error(ResultCode.SYSTEM_ERROR.getCode(), "系统内部错误");
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
    }
} 